part of '../repository.dart';

const _kCollectionLexicalItemIdsKey = 'lexical_item_ids';

const _kCollectionTypeValue = 'collection';

class _CollectionDto extends Equatable implements _CollectionListItemDto {
  const _CollectionDto({
    required this.id,
    required this.titleDtoMap,
    required this.lexicalItemIds,
  });

  @override
  final String id;

  @override
  final BuiltMap<_UILocaleDto, String> titleDtoMap;

  final BuiltSet<String> lexicalItemIds;

  @override
  String get type => _kCollectionTypeValue;

  @override
  List<Object?> get props {
    return [
      id,
      titleDtoMap,
      lexicalItemIds,
    ];
  }

  factory _CollectionDto.fromJson(Map<String, dynamic> json) {
    final titleMap = json[_kCollectionListItemTitlesKey] as Map;

    final titleDtoMap = titleMap.map((uiLocaleString, title) {
      final uiLocale = _UILocaleDto.fromString(uiLocaleString);
      return MapEntry(uiLocale, title as String);
    }).build();

    final lexicalItemIds =
        BuiltSet<String>.from(json[_kCollectionLexicalItemIdsKey]);

    return _CollectionDto(
      id: json[_kCollectionListItemIdKey],
      titleDtoMap: titleDtoMap,
      lexicalItemIds: lexicalItemIds,
    );
  }

  factory _CollectionDto.fromEntity(Collection collection) {
    final titleDtoMap = collection.titles.map((uiLocale, title) {
      final uiLocaleDto = _UILocaleDto.fromEntity(uiLocale);
      return MapEntry(uiLocaleDto, title);
    });

    return _CollectionDto(
      id: collection.id,
      titleDtoMap: titleDtoMap,
      lexicalItemIds: collection.lexicalItemIds,
    );
  }

  @override
  Map<String, dynamic> toJson() {
    final titles = titleDtoMap.map((uiLocaleDto, title) {
      return MapEntry(uiLocaleDto.toString(), title);
    }).toMap();

    return {
      _kCollectionListItemTypeKey: type,
      _kCollectionListItemIdKey: id,
      _kCollectionListItemTitlesKey: titles,
      _kCollectionLexicalItemIdsKey: lexicalItemIds.toList(),
    };
  }

  @override
  Collection toEntity() {
    final titles = titleDtoMap.map((uiLocaleDto, title) {
      return MapEntry(uiLocaleDto.toEntity(), title);
    });

    return Collection(
      id: id,
      titles: titles,
      lexicalItemIds: lexicalItemIds,
    );
  }
}
